import os
import maya.cmds as cmds
import maya.mel as mel
import shutil
# 获取当前文件路径
current_file_path = cmds.file(query=True, sceneName=True)
# 提取文件夹路径
folder_path = os.path.dirname(current_file_path)
current_file_name = os.path.basename(current_file_path).split(".")[0]
current_file_nameType = os.path.basename(current_file_path).split(".")[1]

'''
#复制文件	 有点慢
new_target_file = os.path.join(folder_path,current_file_name + "-BF." + current_file_nameType).replace("\\", "/") 
shutil.copy2(current_file_path, new_target_file)
'''

if current_file_nameType == "ma":
	file_nameType = "mayaAscii"
else:
	file_nameType = "mayaBinary"
# 创建ABC文件夹
folder_name = "ABC"
folder_path = os.path.join(os.path.dirname(current_file_path), folder_name).replace("\\", "/")  
if not os.path.exists(folder_path):
	os.makedirs(folder_path)
	
file_path_ABC_MA = os.path.join(os.path.dirname(current_file_path) ,current_file_name + ".ma").replace("\\", "/")  
all_objectsList = cmds.ls(sl=1)
all_objects =''
for i in all_objectsList:
	all_objects += i+ " "
	print(all_objects)
	abcfilename = current_file_name + "_" + i
	#mel.eval('gpuCache -startTime 0 -endTime 1 -optimize -optimizationThreshold 40000 -writeMaterials -dataFormat ogawa -directory "'+ folder_path +'" -fileName "'+current_file_name+'" "'+all_objects+'";')
	#mel.eval('gpuCache -startTime 0 -endTime 1 -optimize -optimizationThreshold 40000 -writeMaterials -dataFormat ogawa -directory "'+ folder_path +'" -fileName "'+current_file_name+'" -saveMultipleFiles false '+all_objects+';')
	# 执行GPU缓存命令
	#mel.eval('gpuCache -startTime 0 -endTime 1 -optimize -optimizationThreshold 40000 -writeMaterials -dataFormat ogawa -directory "{0}" -fileName "{1}" -saveMultipleFiles false {2};'.format(folder_path, abcfilename, all_objects))
	mel.eval('gpuCache -startTime 0 -endTime 1 -optimize -optimizationThreshold 40000 -writeMaterials -dataFormat ogawa -directory "{0}" -fileName "{1}" -saveMultipleFiles false {2};'.format(folder_path, abcfilename, i))
cmds.file(f=1,new=1)
for i in all_objectsList:
	abcGroup = cmds.group( em = True, name = i )
	abcfilename = current_file_name + "_" + i
	cache_path = os.path.join(folder_path,abcfilename + ".abc").replace("\\", "/")   # 缓存文件的路径
	node_transformName= cmds.createNode('transform', n = abcfilename )
	cache_shape = cmds.createNode('gpuCache', n=abcfilename + "Shape", p = node_transformName )
	# 设置gpuCache节点的缓存路径
	cmds.setAttr(cache_shape + '.cacheFileName', cache_path, type='string')
	cmds.parent(node_transformName,abcGroup)

cmds.file(rename=file_path_ABC_MA)
cmds.file(f=1 ,save=1,options ="v=0;",type=file_nameType)
cmds.file(f=1,new=1)